package com.origin.niuke.dynamic;

import java.util.HashSet;
import java.util.Set;

/**
 * 单词拆分(一)
 * 算法：动态规划、递归
 *
 * @author yezh
 * @date 2023/1/16 22:33
 */
public class NC181 {

    public boolean wordDiv(String s, String[] dic) {
        // write code here
        if ("".equals(s)) return true;
        for (int i = 0; i < s.length(); i++)
            for (int j = 0; j < dic.length; j++)
                if (dic[j].equals(s.substring(0, i + 1))) return wordDiv(s.substring(i + 1), dic);
        return false;
    }

    public boolean wordDiv_dynamic(String s, String[] dic) {
        // write code here
        Set<String> set = new HashSet<>();
        for (String d : dic) set.add(d);
        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;
        for (int end = 1; end <= len; end++)
            for (int start = 0; start < end; start++)
                if (dp[start] && set.contains(s.substring(start, end))) {
                    dp[end] = true;
                    break;
                }
        return dp[len];
    }

}
